package com.ibuonline.search.solr.extend.service;

import java.util.concurrent.ConcurrentHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ibuonline.search.solr.extend.dao.ProductDao;
import com.ibuonline.search.solr.extend.model.Product;

@Service
public class ProductManager {
	private Map<Long, Float> scores = new ConcurrentHashMap<Long, Float>();

	@Autowired
	private ProductDao productDao;

	public void saveProduct(Product product) {
		productDao.save(product);
		scores.put(product.getId(), product.getScore());
	}

	public void deleteProduct(Long id) {
		productDao.delete(id);
		scores.remove(id);
	}

	public float getProductScore(Long id) {
		Float cacheScore = scores.get(id);
		if (scores != null) {
			return cacheScore;
		} else {
			Float score = productDao.getScore(id);
			scores.put(id, score);
			return score;
		}
	}

	public void loadAllProductScores() {
		List<Map<String, Object>> dbScores = productDao.getAllScores();
		for (Map<String, Object> score : dbScores) {
			scores.put((Long) score.get("id"), (Float) score.get("score"));
		}
	}
}
